package com.spring.daily.web.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.spera.genutil.TokenUtil;
import com.spring.daily.web.dao.*;
import com.spring.daily.web.dto.*;
import com.spring.daily.web.model.*;
import com.spring.daily.web.service.DailyService;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.sso.api.web.dao.CFamilyMemberMapper;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.CFamilyMember;

@Service
public class DailyServiceImpl implements DailyService{

	@Resource private WeeklyRecordMapper weeklyRecordMapper;	
	
	@Resource private DailyRecordMapper dailyRecordMapper;	
	
	@Resource private DailyRecordDetailMapper dailyRecordDetailMapper;	

	@Resource private DailyRecordTypeMapper dailyRecordTypeMapper;	
	
	@Resource private WeeklyRecordQuestionMapper weeklyRecordQuestionMapper;	
	
	@Resource private WeeklyRecordDetailMapper weeklyRecordDetailMapper;	
	
	@Resource private CFamilyMemberMapper cfamilyMemberMapper;
	
	@Resource private TeacherMapper teacherMapper;
	
	@Resource private JedisCache jedisCache;
	
	@Resource private SsoMapper ssoMapper;

	@Resource private CourseClassBabyMapper courseClassBabyMapper;
	
	@Resource private CourseClassMapper courseClassMapper;

	@Resource private WeeklyRecordTypeMapper weeklyRecordTypeMapper;
	
	@Override
	public BaseResult daily(DailyParamter dailyParamter) throws Exception{		
		String token = dailyParamter.getToken();
		TokenUtil.checkTokenThrowException(token, jedisCache);

		//如果babyID为空就查家庭所有宝宝
		if(dailyParamter.getBabyID()==null){
			String loginType = jedisCache.hget(token, TokenUtil.LOGIN_TYPE);
			if(loginType.equals("oa")){
				//查询所有
				dailyParamter.setIsSelectAllBaby(1);
			}else{
				//查询部分
				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				String[] babyIDs = ssoMapper.getIDsByID(c_user_id);
				if(babyIDs.length==0){
					return new BaseResult(null);
				}
				dailyParamter.setBabyIDs(babyIDs);
			}
		}else{
			dailyParamter.setBabyIDs(new String[]{dailyParamter.getBabyID()});
		}
		//日记和周记混合记录
		List<Map<String,Object>> dailyList = dailyRecordMapper.selectAllTypeDaily(dailyParamter);		
		return new BaseResult(dailyList);
	}
	
	@Override
	public BaseResult dailyDetail(String dailyRecordID,String token) throws Exception{
		setDailyHasRead(dailyRecordID,token);
		DailyRecordBase daily= dailyRecordMapper.selectDailyByID(dailyRecordID);
		//setDailyBabyImage(daily);		
		return new BaseResult(daily);
	}

	private void setDailyHasRead(String dailyRecordID,String token) throws Exception{
		BaseResult br=TokenUtil.checkTokenBR(token, jedisCache);		
		if(br==null){
			String userType=jedisCache.hget(token,TokenUtil.LOGIN_TYPE);
			if(!userType.equals("oa")){
				DailyRecord dailyRecord=new DailyRecord();
				dailyRecord.setId(dailyRecordID);
				dailyRecord.setHasread(1);
				dailyRecordMapper.updateByPrimaryKeySelective(dailyRecord);
			}
		}
	}
	
	@Override
	public BaseResult delDaily(String dailyRecordID) throws Exception{		
		DailyRecord dailyRecord = dailyRecordMapper.selectByPrimaryKey(dailyRecordID);
		dailyRecord.setEntityavailablestate(20);
		int effect = dailyRecordMapper.updateByPrimaryKey(dailyRecord);		
		return MyTools.checkResult(effect);
	}
	
/*	private void setDailyBabyImage(DailyRecordBase daily){
		String babyID=daily.getBabyid();		
		CFamilyMember cfamilyMember=cfamilyMemberMapper.selectByPrimaryKey(babyID);
		daily.setBabyImage(cfamilyMember.getImageSrc());	
	}*/
	
	@Override
	public BaseResult weeklyDetail(String weeklyRecordID,String token) throws Exception{
		//更新阅读状态
		setWeeklyDetailHasRead(weeklyRecordID,token);		
		WeeklyRecordBase weeklyDaily= weeklyRecordMapper.selectWeekDailyByID(weeklyRecordID);
		//获得家长信息
		getWeeklyDetailParent(weeklyDaily);
		//setWeeklyBabyImage(weeklyDaily);		
		return new BaseResult(weeklyDaily);
	}
	
	private void setWeeklyDetailHasRead(String weeklyRecordID,String token) throws Exception{
		BaseResult br=TokenUtil.checkTokenBR(token, jedisCache);		
		if(br==null){
			String userType=jedisCache.hget(token,TokenUtil.LOGIN_TYPE);
			if(!userType.equals("oa")){
				WeeklyRecordWithBLOBs weeklyRecord=new WeeklyRecordWithBLOBs();
				weeklyRecord.setId(weeklyRecordID);
				weeklyRecord.setHasread(1);
			    weeklyRecordMapper.updateByPrimaryKeySelective(weeklyRecord);
			}
		}		
	}
	
	private void getWeeklyDetailParent(WeeklyRecordBase weeklyDaily) throws Exception{
		CFamilyMember cfamilyMember=cfamilyMemberMapper.selectByPrimaryKey(weeklyDaily.getParentid());
		if(cfamilyMember!=null){
			weeklyDaily.setParentRole(cfamilyMember.getRoleName());
		}	
	}
	
/*	private void setWeeklyBabyImage(WeeklyRecordBase weeklyDaily){
		String babyID=weeklyDaily.getBabyId();		
		CFamilyMember cfamilyMember=cfamilyMemberMapper.selectByPrimaryKey(babyID);
		weeklyDaily.setBabyImage(cfamilyMember.getImageSrc());	
	}*/
	@Override
	public BaseResult delWeeklyRecord(String weeklyRecordID) throws Exception{		
		WeeklyRecord weeklyRecord = weeklyRecordMapper.selectByPrimaryKey(weeklyRecordID);
		weeklyRecord.setEntityavailablestate(20);
		int effect = weeklyRecordMapper.updateByPrimaryKey(weeklyRecord);		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult weeklyDaily(WeeklyRecordWithBLOBs weeklyRecord) throws Exception{
		//weeklyRecord
		int effect = weeklyRecordMapper.updateByPrimaryKeySelective(weeklyRecord);
		return MyTools.checkResult(effect);
	}

	@Override
	public BaseResult courseClass() throws Exception{	
		List<CourseClass> dataset=courseClassMapper.select();
		return new BaseResult(dataset);
	}
	
	@Override
	public BaseResult baby(CourseClassBaby courseClassBaby) throws Exception{	
		List<CourseClassBaby> dataset=courseClassBabyMapper.select(courseClassBaby);
		return new BaseResult(dataset);
	}

	@Override
	public BaseResult dailyType(String token) throws Exception{	
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		List<DailyRecordType> dataset=dailyRecordTypeMapper.selectByUserID(userID);
		return new BaseResult(dataset);
	}

	@Override
	public BaseResult daily(DailyRecordBase daily) throws Exception{
		TokenUtil.checkTokenThrowException(daily.getToken(),jedisCache);
		generateTeacherData(daily);		
		addDaily(daily);
		addDailyItem(daily);		
		return new BaseResult();
	}
	private void generateTeacherData(DailyRecordBase daily) throws Exception{
		String teacherID = jedisCache.hget(daily.getToken(), TokenUtil.USER_ID);
		String teacherName = jedisCache.hget(daily.getToken(), TokenUtil.USER_NAME);
		daily.setTeacherName(teacherName);
		daily.setTeacherid(teacherID);
	}
	
	private void addDaily(DailyRecordBase daily) throws Exception{
		DailyRecord dailyRecord=new DailyRecord(daily);	
		String dailyRecordID = UUID.randomUUID().toString();
		dailyRecord.setId(dailyRecordID);
		int effect = dailyRecordMapper.insert(dailyRecord);
		MyTools.checkEffect(effect);
		daily.setId(dailyRecordID);
	};

	private void addDailyItem(DailyRecordBase daily) throws Exception{
		 for(DailyRecordDetailBase dailyRecordDetailBase:daily.getDetail()){		 
			 if(dailyRecordDetailBase.getTypeid()==null){
				 addDailyType(dailyRecordDetailBase,daily);
			 }
			 addDailyDetail(dailyRecordDetailBase,daily);
		 }
	}
	
	private void addDailyType(DailyRecordDetailBase dailyRecordDetailBase,DailyRecordBase daily) throws Exception{
		 String dailyRecordTypeID = UUID.randomUUID().toString();
		 DailyRecordType dailyRecordType=new DailyRecordType(dailyRecordDetailBase);
		 dailyRecordType.setId(dailyRecordTypeID);		 		 
		 dailyRecordType.setInitialoperatorid(daily.getTeacherid());
		 dailyRecordType.setInitialoperatorname(daily.getTeacherName());
		 
		 int effect=dailyRecordTypeMapper.insert(dailyRecordType);
		 MyTools.checkEffect(effect);
		 dailyRecordDetailBase.setTypeid(dailyRecordTypeID);
	}
	
	private void addDailyDetail(DailyRecordDetailBase dailyRecordDetailBase,DailyRecordBase daily) throws Exception{
		 DailyRecordDetail dailyRecordDetail=new DailyRecordDetail(dailyRecordDetailBase,daily.getId());
		 int effect=dailyRecordDetailMapper.insert(dailyRecordDetail);	
		 MyTools.checkEffect(effect);
	}
	
	@Override
	public BaseResult weeklyQuestion(String parentWeeklyRecordTypeID) throws Exception{	
		List<WeeklyRecordType> dataset=weeklyRecordQuestionMapper.select(parentWeeklyRecordTypeID);
		return new BaseResult(dataset);
	}
	
	@Override
	public BaseResult weeklyDaily(WeeklyRecordBase weeklyRecordBase) throws Exception{	
		TokenUtil.checkTokenThrowException(weeklyRecordBase.getToken(),jedisCache);
		generateTeacherData(weeklyRecordBase);		
		addWeeklyDaily(weeklyRecordBase);
		addWeeklyDailyItem(weeklyRecordBase);		
		return new BaseResult();
	}
	
	private void generateTeacherData(WeeklyRecordBase weeklyRecordBase) throws Exception{
		String teacherID = jedisCache.hget(weeklyRecordBase.getToken(), TokenUtil.USER_ID);
		String teacherName = jedisCache.hget(weeklyRecordBase.getToken(), TokenUtil.USER_NAME);
		weeklyRecordBase.setTeacherName(teacherName);
		weeklyRecordBase.setTeacherId(teacherID);
	}
	
	private void addWeeklyDaily(WeeklyRecordBase weeklyRecordBase) throws Exception{
		WeeklyRecordWithBLOBs weeklyRecord=new WeeklyRecordWithBLOBs(weeklyRecordBase);	
		setWeek(weeklyRecord);
		String weeklyDailyRecordID = UUID.randomUUID().toString();
		weeklyRecord.setId(weeklyDailyRecordID);;
		int effect = weeklyRecordMapper.insert(weeklyRecord);
		MyTools.checkEffect(effect);
		weeklyRecordBase.setId(weeklyDailyRecordID);
	}
	private void setWeek(WeeklyRecordWithBLOBs weeklyRecordWithBLOBs) throws Exception{
		CourseClassBaby param=new CourseClassBaby();
		param.setBabyId(weeklyRecordWithBLOBs.getBabyId());
		List<CourseClassBaby> list=courseClassBabyMapper.selectByPara(param);
		if(list.size()>0){
			CourseClassBaby courseClassBaby=list.get(0);
			long enterDateLong=courseClassBaby.getEnterDate();
			long recordDateLong =weeklyRecordWithBLOBs.getRecordDate().getTime();
			long week=(recordDateLong/1000-enterDateLong)/(3600*24*7)+1;
			weeklyRecordWithBLOBs.setWeek((int)week);
		}
	}	
	private void addWeeklyDailyItem(WeeklyRecordBase weeklyRecordBase) throws Exception{
		 for(WeeklyRecordQuestionBase weeklyRecordQuestionBase:weeklyRecordBase.getQuestion()){		 
			 WeeklyRecordDetail weeklyRecordDetail=new WeeklyRecordDetail(weeklyRecordQuestionBase,weeklyRecordBase.getId());
			 int effect=weeklyRecordDetailMapper.insert(weeklyRecordDetail);
			 MyTools.checkEffect(effect);
		 }
	}
	
	@Override
	public BaseResult teacher(String courseClassid) throws Exception{	
		List<Teacher> dataset=teacherMapper.selectByClassID(courseClassid);
		return new BaseResult(dataset);
	}
	
	@Override
	public BaseResult selectParent() throws Exception{
		List<WeeklyRecordType> dataset = weeklyRecordTypeMapper.selectParent();
		return new BaseResult(dataset);
	}
	
}
